/* Create thread that returns value to calling code
 * computes prime numbers in thread
 */

#include <stdio.h>
#include <pthread.h>

/* compute successive prime no */
void *
compute_prime (void *arg)
{
    int candidate = 2;
    int n = *((int *) arg);

    while (1) {
	int factor;
	int is_prime = 1;

	/* test primality by successive division */
	for (factor = 2; factor < candidate; ++factor) {
	    if (candidate % factor == 0) {
		is_prime =0;
		break;
	    }
	}

	/* is this prime numbers we are looking for */
	if (is_prime) {
	    if (--n == 0) {
	    /* return the desired prime number as thread return value */
		return (void *) candidate;
	    }
	}
	++candidate;
    }
    return NULL;
}

int main (int argc, char **argv)
{
    pthread_t thread;
    int which_prime = 5;
    int prime;

    /* start computing thread, up to 5000 th prime no */
    pthread_create (&thread, NULL, &compute_prime, &which_prime);

    /* wail for the prime number thread to complete and get the result */
    pthread_join (thread, (void *) &prime);

    /* print largest prime number it computed */
    printf ("The %d th prime numbers is %d\n", which_prime, prime);

    return 0;
}
